package com.mixsmart.web.msgpush.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.comet4j.core.CometConnection;
import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;

import com.mixsmart.utils.CollectionUtils;
import com.mixsmart.utils.StringUtils;
import com.mixsmart.web.msgpush.ISendMessage;
import com.mixsmart.web.msgpush.MessageType;
import com.mixsmart.web.msgpush.SendData;

/**
 * 通过Comet4j插件发消息
 * @author lmq
 * @version 1.0
 * @since JDK版本大于等于1.6
 * <p>2016年3月29日</p>
 */
public class Comet4jSendMessage implements ISendMessage {
	
	private static final Logger logger = Logger.getLogger(Comet4jSendMessage.class);
	
	private CometEngine cometEngine;
	
	/**
	 * 通过Comet4j插件发消息(构造函数)
	 */
	public Comet4jSendMessage() {
		cometEngine = CometContext.getInstance().getEngine();
	}

	@Override
	public void send(MessageType messageType, String destUserId, String content) {
		this.send(messageType, destUserId, this.getSendData(content));
	}

	@Override
	public void sendMany(MessageType messageType, List<String> destUserIds, String content) {
		this.sendMany(messageType, destUserIds, this.getSendData(content));
	}

	@Override
	public void sendAll(String content) {
		this.sendAll(this.getSendData(content));
	}

	@Override
	public void send(MessageType messageType, String destUserId, SendData sendData) {
		logger.debug("正在给["+destUserId+"]发送消息...");
		if(null != messageType && StringUtils.isNotEmpty(destUserId) && null != sendData) {
			CometConnection cc = cometEngine.getConnection(destUserId);
			cometEngine.sendTo(messageType.getValue(), cc, sendData);
			logger.debug("发送消息---[成功]---");
		} else {
			logger.error("发送目标或发送内容为空...");
		}
	}

	@Override
	public void sendMany(MessageType messageType, List<String> destUserIds, SendData sendData) {
		logger.debug("正在给多人发送消息...");
		if(null != messageType && CollectionUtils.isNotEmpty(destUserIds) && null != sendData) {
			List<CometConnection> ccs = new ArrayList<CometConnection>();
			for (String userId : destUserIds) {
				CometConnection cc = cometEngine.getConnection(userId);
				ccs.add(cc);
			}
			cometEngine.sendTo(messageType.getValue(), ccs, sendData);
			logger.debug("多人发送消息---[成功]---");
		} else {
			logger.error("发送目标或发送内容为空...");
		}
	}

	@Override
	public void sendAll(SendData sendData) {
		logger.debug("正在全发消息...");
		if(null != sendData) {
			cometEngine.sendToAll(MessageType.NOTICE.getValue(), sendData);
			logger.debug("全发消息---[成功]---");
		} else {
			logger.error("发送内容为空...");
		}
	}

	/**
	 * 获取数据
	 * @param content 内容
	 * @return 返回发送对象
	 */
	private SendData getSendData(String content) {
		return new SendData(content, content);
	}
}
